package com.cya.forumproject.services.impl;

import com.cya.forumproject.common.AppResult;
import com.cya.forumproject.common.ResultCode;
import com.cya.forumproject.dao.ArticleMapper;
import com.cya.forumproject.exception.ApplicationException;
import com.cya.forumproject.model.Article;
import com.cya.forumproject.model.Board;
import com.cya.forumproject.model.User;
import com.cya.forumproject.services.IArticleService;
import com.cya.forumproject.services.IBoradService;
import com.cya.forumproject.services.IUserService;
import com.cya.forumproject.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author ：陈奕安（3048279304@qq.com）
 * @date ：Created in 2025/9/21 19:27
 * @description：
 * @modified By：
 * @version:
 */
@Slf4j
@Service
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;
    //用户和板块操作
    @Resource
    private IBoradService boradService;
    @Resource
    private IUserService userService;


    @Override
    public void creat(Article article) {

        //非空校验
         if (article==null||article.getUserId()==null||article.getBoardId()==null
         || StringUtil.isEmpty(article.getTitle())
         ||StringUtil.isEmpty(article.getContent())){
             //打印日志
             log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
             //抛出异常
             throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
         }
         article.setVisitCount(0);
         article.setReplyCount(0);
         article.setLikeCount(0);
         article.setDeleteState((byte) 0);
         article.setState((byte) 0);
        Date date=new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);
        //写入数据库
        int i = articleMapper.insertSelective(article);
        if (i<=0){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        User user = userService.selectById(article.getUserId());
        //没有找到指定用户信息
        if (user==null){
            log.warn(ResultCode.FAILED_CREATE.toString()+", 发帖失败,userId= "+article.getUserId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新用户发帖数

        userService.addOneArticleCountById(user.getId());
        //获取板块信息
        Board board = boradService.selectById(article.getBoardId());
        //数据库是否有对应的板块
        if (board==null){
            log.warn(ResultCode.FAILED_CREATE.toString()+", 发帖失败,boardId= "+article.getBoardId());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }
        //更新板块数量
        boradService.addOneArticleCountById(board.getId());
        log.info(ResultCode.SUCCESS.toString()+",userId= "
                +article.getUserId()+", boardId= "+article.getBoardId()+",article id ="+article.getId()+" 发帖成功");
    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();

        return articles;

    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
//        非空校验
        if (boardId==null||boardId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验板块是否存在
        Board board = boradService.selectById(boardId);
        if (board==null){
        log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+", board id="+boardId);
        throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        List<Article> articles=articleMapper.selectAllByBoardId(boardId);
        return articles;

    }

    @Override
    public List<Article> selectByUserId(Long userId) {
        if (userId==null||userId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);
        if (user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectByUserId(userId);

        return articles;
    }

    /**
     * 根据id查询帖子详情
     * @param id
     * @return
     */
    @Override
    public Article selectDetailById(Long id) {
        if (id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        查找帖子详情
        Article article = articleMapper.selectDetailById(id);
//        判断是否为空
        if (article==null){
//            打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
//            抛异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
//        更新访问帖子次数
        Article article1=new Article();
        article1.setId(id);
        article1.setVisitCount(article.getVisitCount()+1);
//        保存到数据库
        int i = articleMapper.updateByPrimaryKeySelective(article1);
        if (i!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());

            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
//        为返回的对象访问次数更新
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    /**
     * 修改帖子
     * @param id
     * @param title
     * @param content
     */

    @Override
    public void modify(Long id, String title, String content) {
        if (id==null||id<=0||StringUtil.isEmpty(title)
        ||StringUtil.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article=new Article();

        article.setId(id);//id
        article.setTitle(title);//标题
        article.setContent(content);//正文
        article.setUpdateTime(new Date());//修改时间

        int row = articleMapper.updateByPrimaryKeySelective(article);
        if (row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    /**
     * 用帖子id查询帖子
     * @param id
     * @return
     */
    @Override
    public Article selectById(Long id) {
        if (id==null||id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        Article article = articleMapper.selectByPrimaryKey(id);

        return article;
    }

    @Override
    public void thumbsUpById(Long id) {

        //帖子不存在
        if (id==null||id<=0){
            log.warn(ResultCode. FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_PARAMS_VALIDATE));
        }
//        获取帖子详情状态异常
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article==null||article.getDeleteState()==1){
            log.warn(ResultCode. FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));

        }
        Article updateArticle=new Article();
        updateArticle.setId(id);
        updateArticle.setLikeCount(article.getLikeCount()+1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void deleteById(Long id) {
        //帖子不存在
        if (id==null||id<=0){
            log.warn(ResultCode. FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_PARAMS_VALIDATE));
        }

        //        获取帖子详情状态异常
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article==null||article.getDeleteState()==1){
            log.warn(ResultCode. FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_ARTICLE_NOT_EXISTS));
        }
        Article updateArticle=new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        updateArticle.setUpdateTime(new Date());
//        调用dao
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row!=1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
        //更新板块数和用户帖子数
        boradService.subOneArticleCountId(article.getBoardId());
        userService.subOneArticleCountId(article.getUserId());
        log.info(" 删除成功!!!");
    }

    @Override
    public void addOneReplyCountById(Long id) {
        //帖子不存在
        if (id==null||id<=0){
            log.warn(ResultCode. FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_PARAMS_VALIDATE));
        }
        //        获取帖子详情状态异常
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article==null||article.getDeleteState()==1){
            log.warn(ResultCode. FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_ARTICLE_NOT_EXISTS));
        }
//        帖子已经封贴
        if (article.getState()==1){
            log.warn(ResultCode. FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_ARTICLE_BANNED));
        }
        Article updateArticle=new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        articleMapper.updateByPrimaryKeySelective(updateArticle);
    }
}